package ssm.service.Impl;

import org.springframework.transaction.annotation.Transactional;
import ssm.model.entity.User;
import ssm.mapper.UserMapper;
import ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ssm.utils.CommonUtils;
import ssm.utils.JWTUtils;

import java.util.Date;
import java.util.Map;
import java.util.Random;

/**
 * 1、启动类添加注解
 * 1、@MapperScan("ssm.mapper")// 开启扫描包
 * 2、@EnableTransactionManagement //启动事务管理
 * 2、在实现类中添加注解
 * 1、@Transactional
 */

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;


    @Override
    public int save(Map<String, String> userInfo) {
        User user = parseToUser(userInfo);
        if (user != null) {
            return userMapper.save(user);
        } else {
            return -1;
        }

    }

    private User parseToUser(Map<String, String> userInfo) {
        if (userInfo.containsKey("phone") && userInfo.containsKey("pwd") && userInfo.containsKey("name")) {
            User user = new User();
            user.setName(userInfo.get("name"));
            user.setHeadImg(getRandomimg());
            user.setCreateTime(new Date());
            user.setPhone(userInfo.get("phone"));
            String pwd = userInfo.get("pwd");
            user.setPwd(CommonUtils.MD5(pwd));
            return user;
        } else {
            return null;
        }

    }

    @Override
    public User findByPhone(String phone) {
        return null;
    }

    @Override
    public String findByPhoneAndPwd(String phone, String pwd) {
        User user = userMapper.findByPhoneAndPwd(phone, CommonUtils.MD5(pwd));
        if (user == null) {
            return null;
        } else {
            // 登录成功了，生成token信息
            String token = JWTUtils.geneJsonWebToken(user);
            return token;
        }
    }

    @Override
    public User findByUserId(Integer user_id) {
        User user = userMapper.findByUserId(user_id);
        user.setPwd("");
        return user;
    }

    private static final String[] headImg = {
            "https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/default/head_img/12.jpeg",
            "https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/default/head_img/11.jpeg",
            "https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/default/head_img/13.jpeg",
            "https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/default/head_img/14.jpeg",
            "https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/default/head_img/15.jpeg"
    };

    private String getRandomimg() {
        int size = headImg.length;
        Random random = new Random();
        int i = random.nextInt(size);
        return headImg[i];
    }

}
